import config from "config";
import { prisma } from "../database/generated/prisma-client";
import path from "path";
import http from "http";
import logger from "./log";

const myConfig = config.util.loadFileConfigs(path.join(__dirname, "..", "config"));
const { statusPort = 8008 } = myConfig;

const enableStatusReportServer = () => {
    const server = http.createServer(async (req, res) => {
        if (req.url !== "/status") {
            res.writeHead(404);
            res.end();
            return;
        }
        const networks = await prisma.networks();
        const result = networks.map((network) => ({
            id: network.id,
            blockCount: network.BLOCK_COUNT,
            transactionCount: network.TRANS_COUNT,
            syncedBlockHeight: network.SYNCED_HEIGHT,
            syncedTransactionCount: network.SYNCED_TX_COUNT,
        }));
        const currentSubscriberNames = myConfig.subscribers.map((subscriber) => subscriber.name);
        const subscribers = await prisma.subscribers({ where: { name_in: currentSubscriberNames } })
            .$fragment(`
                fragment SubscriberWithoutId on Subscriber {
                    name
                    url
                    blockchainIds
                    latestReceivedBlockHeights
                    interestingBlockHeightRange
                }
            `);
        res.writeHead(200, { "Content-Type": "application/json" });
        res.write(JSON.stringify({
            blockchain: result,
            subscribers, 
            timestamp: new Date().toISOString()
        }, null, 2));
        res.end();
    });
    server.on("error", (err) => {
        logger.error(`Falied to start the status report server with the error: ${err}`);
    });
    server.listen(statusPort, () => {
        logger.info(`Started the status report server and listening on port ${statusPort}`);
    });
};

export default enableStatusReportServer;